package com.file.parser;


import com.file.bo.AppTaxIncome;
import com.file.bo.AppTaxIncomeDetail;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;

/**
 * 个税收入明细html解析
 * @author anyspa
 */

@Slf4j
public class AppTaxIncomeDetailHtmlParser {


    private AppTaxIncomeHtmlParser appTaxIncomeHtmlParser = new AppTaxIncomeHtmlParser();

    public ResponseData<String> parseAppTaxIncomeDetailHtmlToJson(String daId, String filePath) {
        log.info("parseAppTaxIncomeDetailHtmlToJson started, daId:{}", daId);
        String json;

        try {
            if (filePath.contains("tax_income_detail") || filePath.contains("app_tax_detail")) {
                AppTaxIncomeDetail appTaxIncomeDetail = parseAppTaxIncomeDetailHtml(filePath);
                json = JsonUtils.convertObjectToJson(appTaxIncomeDetail);
            } else if (filePath.contains("tax_income") || filePath.contains("app_tax_income")) {
                AppTaxIncome appTaxIncome = appTaxIncomeHtmlParser.parseAppTaxIncomeHtml(filePath);
                json = JsonUtils.convertObjectToJson(appTaxIncome);
            } else {
                throw new RuntimeException("the file name is not supported");
            }
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseAppTaxIncomeDetailHtmlToJson failed", e);
            return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseAppTaxIncomeDetailHtmlToJson completed, daId:{}, json:{}", daId, json);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    public AppTaxIncomeDetail parseAppTaxIncomeDetailHtml(String filePath) throws IOException {
        File input = new File(filePath);
        AppTaxIncomeDetail appTaxIncome = new AppTaxIncomeDetail();
        AppTaxIncomeDetail.TaxDetail taxDetail = new AppTaxIncomeDetail.TaxDetail();
        AppTaxIncomeDetail.TaxDetailBaseInfo taxDetailBaseInfo = new AppTaxIncomeDetail.TaxDetailBaseInfo();

        Document doc = Jsoup.parse(input, "UTF-8");
//        // 纳税明细信息 + 申报日期、税款所属期
//        Elements elements = doc.select(".c-group-container:not(.c-group-container-tax):not(.srmx)");
//        elements.forEach(element -> {
//            Elements cItemBoxSelects = element.select(".c-item-box");
//            cItemBoxSelects.forEach(element1 -> {
//                String titleText = element1.select(".c-item-box-title").text();
//                String infoText = element1.select(".c-item-box-info").text();
//                if (titleText.contains("收入") && StringUtils.isBlank(taxDetail.getIncome())) {
//                    taxDetail.setIncome(infoText);
//                } else if (titleText.contains("已申报税额") && StringUtils.isBlank(taxDetail.getDeclaredTax())) {
//                    taxDetail.setDeclaredTax(infoText);
//                }  else if (titleText.contains("申报日期") && StringUtils.isBlank(taxDetailBaseInfo.getDeclarationDate())) {
//                    taxDetailBaseInfo.setDeclarationDate(infoText);
//                } else if (titleText.contains("税款所属期") && StringUtils.isBlank(taxDetailBaseInfo.getTaxPeriod())) {
//                    taxDetailBaseInfo.setTaxPeriod(infoText);
//                }
//            });
//        });
//
//        // 纳税明细-基础情况
//        Element taxDetailBaseInfoElement = doc.selectFirst(".c-group-container.c-group-container-tax");
//        if (taxDetailBaseInfoElement != null) {
//            Elements cItemBoxSelects = taxDetailBaseInfoElement.select(".c-item-box");
//            cItemBoxSelects.forEach(element -> {
//                String titleText = element.select(".c-item-box-title").text();
//                String infoText = element.select(".c-item-box-info").text();
//                if (titleText.contains("所得项目小类") && StringUtils.isBlank(taxDetailBaseInfo.getIncomeItemSubCategory())) {
//                    taxDetailBaseInfo.setIncomeItemSubCategory(infoText);
//                } else if (titleText.contains("扣缴义务人名称") && StringUtils.isBlank(taxDetailBaseInfo.getWithholdingAgent())) {
//                    taxDetailBaseInfo.setWithholdingAgent(infoText);
//                } else if (titleText.contains("扣缴义务人纳税人识别号") && StringUtils.isBlank(taxDetailBaseInfo.getWithholdingAgentIdentifier())) {
//                    taxDetailBaseInfo.setWithholdingAgentIdentifier(infoText);
//                } else if (titleText.contains("主管税务机关") && StringUtils.isBlank(taxDetailBaseInfo.getCompetentTaxAuthority())) {
//                    taxDetailBaseInfo.setCompetentTaxAuthority(infoText);
//                } else if (titleText.contains("申报渠道") && StringUtils.isBlank(taxDetailBaseInfo.getDeclarationChannel())) {
//                    taxDetailBaseInfo.setDeclarationChannel(infoText);
//                }
//            });
//        }

        Elements elements = doc.select(".c-item-box");
        for (Element element : elements) {
            if (element.children().size() == 2) {
                String titleText = element.children().get(0).text();
                String infoText = element.children().get(1).text();
                if (titleText.contains("收入") && StringUtils.isBlank(taxDetail.getIncome())) {
                    taxDetail.setIncome(infoText);
                } else if (titleText.contains("已申报税额") && StringUtils.isBlank(taxDetail.getDeclaredTax())) {
                    taxDetail.setDeclaredTax(infoText);
                } else if (titleText.contains("申报日期") && StringUtils.isBlank(taxDetailBaseInfo.getDeclarationDate())) {
                    taxDetailBaseInfo.setDeclarationDate(infoText);
                } else if (titleText.contains("税款所属期") && StringUtils.isBlank(taxDetailBaseInfo.getTaxPeriod())) {
                    taxDetailBaseInfo.setTaxPeriod(infoText);
                } else if (titleText.contains("所得项目小类") && StringUtils.isBlank(taxDetailBaseInfo.getIncomeItemSubCategory())) {
                    taxDetailBaseInfo.setIncomeItemSubCategory(infoText);
                } else if (titleText.contains("扣缴义务人名称") && StringUtils.isBlank(taxDetailBaseInfo.getWithholdingAgent())) {
                    taxDetailBaseInfo.setWithholdingAgent(infoText);
                } else if (titleText.contains("扣缴义务人纳税人识别号") && StringUtils.isBlank(taxDetailBaseInfo.getWithholdingAgentIdentifier())) {
                    taxDetailBaseInfo.setWithholdingAgentIdentifier(infoText);
                } else if (titleText.contains("主管税务机关") && StringUtils.isBlank(taxDetailBaseInfo.getCompetentTaxAuthority())) {
                    taxDetailBaseInfo.setCompetentTaxAuthority(infoText);
                } else if (titleText.contains("申报渠道") && StringUtils.isBlank(taxDetailBaseInfo.getDeclarationChannel())) {
                    taxDetailBaseInfo.setDeclarationChannel(infoText);
                }
            }
        }

        if (hasTaxCalculation(doc)) {
            // 有税款计算case
            processHasTaxCalculationCase(doc, appTaxIncome);
        } else {
            // 无税款计算case
            processHasNoTaxCalculationCase(doc, appTaxIncome);
        }

        appTaxIncome.setTaxDetail(taxDetail);
        appTaxIncome.setTaxDetailBaseInfo(taxDetailBaseInfo);
        return appTaxIncome;
    }

    private boolean hasTaxCalculation(Document doc) {
        Elements elements = doc.select(".link-line");
        for (Element element : elements) {
            String text = element.text();
            if (text.contains("查看税款计算")) {
                return false;
            }
        }
        return true;
    }

    private void processHasTaxCalculationCase(Document doc, AppTaxIncomeDetail appTaxIncomeDetail) {
        AppTaxIncomeDetail.CurrentIncomeAndDeductionsDetail currentIncomeAndDeductionsDetail =
                new AppTaxIncomeDetail.CurrentIncomeAndDeductionsDetail();
        AppTaxIncomeDetail.CurrentIncomeAndDeductionsDetail.CurrentSpecialDeduction currentSpecialDeduction =
                new AppTaxIncomeDetail.CurrentIncomeAndDeductionsDetail.CurrentSpecialDeduction();
        AppTaxIncomeDetail.TaxCalculation taxCalculation = new AppTaxIncomeDetail.TaxCalculation();

        Elements srmxElements = doc.select(".c-group-container.srmx");
        if (srmxElements.size() == 2) {
            // 本期收入与扣除详情
            Elements cItemBoxSelects = srmxElements.get(0).select(".c-item-box");
            cItemBoxSelects.forEach(element -> {
                String titleText = element.select(".c-item-box-title").text();
                String infoText = element.select(".c-item-box-info").text();
                if (titleText.contains("免税收入") && StringUtils.isBlank(currentIncomeAndDeductionsDetail.getCurrentTaxExemptIncome())) {
                    currentIncomeAndDeductionsDetail.setCurrentTaxExemptIncome(infoText);
                } else if (titleText.contains("收入") && StringUtils.isBlank(currentIncomeAndDeductionsDetail.getCurrentIncome())) {
                    currentIncomeAndDeductionsDetail.setCurrentIncome(infoText);
                } else if (titleText.contains("减除费用") && StringUtils.isBlank(currentIncomeAndDeductionsDetail.getCurrentExpenseDeduction())) {
                    currentIncomeAndDeductionsDetail.setCurrentExpenseDeduction(infoText);
                } else if (titleText.contains("专项扣除") && StringUtils.isBlank(currentSpecialDeduction.getSpecialDeductionTotal())) {
                    currentSpecialDeduction.setSpecialDeductionTotal(infoText);
                    parseSpecialDeduction(doc, currentSpecialDeduction);
                } else if (titleText.contains("其他扣除") && StringUtils.isBlank(currentIncomeAndDeductionsDetail.getCurrentOtherDeduction())) {
                    currentIncomeAndDeductionsDetail.setCurrentOtherDeduction(infoText);
                } else if (titleText.contains("准予扣除的捐赠") && StringUtils.isBlank(currentIncomeAndDeductionsDetail.getDonationItemsOfCurrentDeducted())) {
                    currentIncomeAndDeductionsDetail.setDonationItemsOfCurrentDeducted(infoText);
                }
            });

            Element totalLineElement = srmxElements.get(0).selectFirst(".c-total-line");
            if (totalLineElement != null) {
                String text = totalLineElement.select(".c-total-line-title").text();
                if (text.contains("应纳税所得额")) {
                    String infoText = totalLineElement.select(".c-total-line-info").text();
                    currentIncomeAndDeductionsDetail.setTaxableIncome(infoText);
                }
            }

            // 税款计算
            cItemBoxSelects = srmxElements.get(1).select(".c-item-box");
            cItemBoxSelects.forEach(element -> {
                String titleText = element.select(".c-item-box-title").text();
                String infoText = element.select(".c-item-box-info").text();
                if (titleText.contains("应纳税所得额") && StringUtils.isBlank(taxCalculation.getTaxableIncome())) {
                    taxCalculation.setTaxableIncome(infoText);
                } else if (titleText.contains("税率/预扣率") && StringUtils.isBlank(taxCalculation.getTaxRate())) {
                    taxCalculation.setTaxRate(infoText);
                } else if (titleText.contains("速算扣除数") && StringUtils.isBlank(taxCalculation.getQuickCalculationDeduction())) {
                    taxCalculation.setQuickCalculationDeduction(infoText);
                } else if (titleText.contains("应纳税额") && StringUtils.isBlank(taxCalculation.getTaxPayable())) {
                    taxCalculation.setTaxPayable(infoText);
                } else if (titleText.contains("减免税额") && StringUtils.isBlank(taxCalculation.getTaxExempt())) {
                    taxCalculation.setTaxExempt(infoText);
                } else if (titleText.contains("已缴税额") && StringUtils.isBlank(taxCalculation.getTaxPaid())) {
                    taxCalculation.setTaxPaid(infoText);
                }
            });

            totalLineElement = srmxElements.get(1).selectFirst(".c-total-line");
            if (totalLineElement != null) {
                String text = totalLineElement.select(".c-total-line-title").text();
                if (text.contains("申报税额")) {
                    String infoText = totalLineElement.select(".c-total-line-info").text();
                    taxCalculation.setTaxDeclared(infoText);
                }
            }
        }
        currentIncomeAndDeductionsDetail.setCurrentSpecialDeduction(currentSpecialDeduction);
        appTaxIncomeDetail.setCurrentIncomeAndDeductionsDetail(currentIncomeAndDeductionsDetail);
        appTaxIncomeDetail.setTaxCalculation(taxCalculation);
    }

    private void parseSpecialDeduction(Document doc, AppTaxIncomeDetail.CurrentIncomeAndDeductionsDetail.CurrentSpecialDeduction currentSpecialDeduction) {
        Elements elements = doc.select(".collapse-content p.c-item");
        elements.forEach(element -> {
            Elements spanElement = element.select("span");
            if (spanElement.size() >= 2) {
                String titleText = spanElement.get(0).text();
                String infoText = spanElement.get(1).text();
                if (titleText.contains("基本养老保险")) {
                    currentSpecialDeduction.setBasePensionActual(infoText);
                } else if (titleText.contains("基本医疗保险")) {
                    currentSpecialDeduction.setBaseMedicalActual(infoText);
                } else if (titleText.contains("失业保险")) {
                    currentSpecialDeduction.setUnemploymentActual(infoText);
                } else if (titleText.contains("住房公积金")) {
                    currentSpecialDeduction.setHousingFund(infoText);
                }
            }
        });
    }

    private void processHasNoTaxCalculationCase(Document doc, AppTaxIncomeDetail appTaxIncomeDetail) {
        AppTaxIncomeDetail.CurrentIncomeAndDeductionsDetail currentIncomeAndDeductionsDetail =
                new AppTaxIncomeDetail.CurrentIncomeAndDeductionsDetail();
        AppTaxIncomeDetail.CurrentIncomeAndDeductionsDetail.CurrentSpecialDeduction currentSpecialDeduction =
                new AppTaxIncomeDetail.CurrentIncomeAndDeductionsDetail.CurrentSpecialDeduction();
        AppTaxIncomeDetail.TaxCalculation taxCalculation = new AppTaxIncomeDetail.TaxCalculation();

        // 本期收入与扣除详情
        Element srmxElement = doc.selectFirst(".c-group-container.srmx");
        if (srmxElement !=null ) {
            Elements cItemBoxSelects = srmxElement.select(".c-item-box");
            cItemBoxSelects.forEach(element -> {
                String titleText = element.select(".c-item-box-title").text();
                String infoText = element.select(".c-item-box-info").text();
                if (titleText.contains("免税收入") && StringUtils.isBlank(currentIncomeAndDeductionsDetail.getCurrentTaxExemptIncome())) {
                    currentIncomeAndDeductionsDetail.setCurrentTaxExemptIncome(infoText);
                } else if (titleText.contains("收入") && StringUtils.isBlank(currentIncomeAndDeductionsDetail.getCurrentIncome())) {
                    currentIncomeAndDeductionsDetail.setCurrentIncome(infoText);
                } else if (titleText.contains("减除费用") && StringUtils.isBlank(currentIncomeAndDeductionsDetail.getCurrentExpenseDeduction())) {
                    currentIncomeAndDeductionsDetail.setCurrentExpenseDeduction(infoText);
                } else if (titleText.contains("专项扣除") && StringUtils.isBlank(currentSpecialDeduction.getSpecialDeductionTotal())) {
                    currentSpecialDeduction.setSpecialDeductionTotal(infoText);
                    parseSpecialDeduction(doc, currentSpecialDeduction);
                } else if (titleText.contains("其他扣除") && StringUtils.isBlank(currentIncomeAndDeductionsDetail.getCurrentOtherDeduction())) {
                    currentIncomeAndDeductionsDetail.setCurrentOtherDeduction(infoText);
                } else if (titleText.contains("准予扣除的捐赠") && StringUtils.isBlank(currentIncomeAndDeductionsDetail.getDonationItemsOfCurrentDeducted())) {
                    currentIncomeAndDeductionsDetail.setDonationItemsOfCurrentDeducted(infoText);
                }
            });
        }

        Element el = doc.selectFirst(".manual-collapse-component.tax-calc-collapse");
        if (el != null) {
            String text = el.select(".collapse-title > span").text();
            if (text.contains("本期专项扣除")) {
                currentSpecialDeduction.setSpecialDeductionTotal(el.select(".collapse-title > a > span").text());
                parseSpecialDeduction(doc, currentSpecialDeduction);
            }
        }

        currentIncomeAndDeductionsDetail.setCurrentSpecialDeduction(currentSpecialDeduction);
        appTaxIncomeDetail.setCurrentIncomeAndDeductionsDetail(currentIncomeAndDeductionsDetail);
        appTaxIncomeDetail.setTaxCalculation(taxCalculation);
    }

    public static void main(String[] args) {
        AppTaxIncomeDetailHtmlParser appTaxIncomeDetailHtmlParser = new AppTaxIncomeDetailHtmlParser();
        AppTaxIncomeHtmlParser appTaxIncomeHtmlParser = new AppTaxIncomeHtmlParser();
        String json = appTaxIncomeDetailHtmlParser.parseAppTaxIncomeDetailHtmlToJson("", "D:\\data\\file\\app-tax-detail\\zd4t8pen1790950425816961024_031c7fcac10d8eaf849f89897377008c_app-tax-detail_extra_origins\\tax_income_detail_1_2.html").getData();
        System.out.println(json);
    }
}
